"use strict";

//resetPropertyList isn't strictly needed under normal circumstances, but makes "refresh" work. 
//This makes iterating on the web side for dev easier as well as preventing 
//any problems caused by users right-clicking and hitting refresh for some reason


preDocumentStartupPromise = Promise.allFinish(
	[
		resetPropertyList(),
		initialiseBuildState(), //Should be done before anything else (except the reset) so we know whether to make a fuss about errors.
		StartupStart()
	]);

startupPreImportTasks.push(initialiseLoadingScreen);

startupPreImportTasks.push(initialiseLanguageClasses);

startupPreImportTasks.push(initialiseDeliveryClasses);

startupPreImportTasks.push(initialiseUpdateHtmlImport);

//Must be done before property load, since we assume that elements have been replaced in property code.
startupPrePropertyLoadTasks.push(initialiseGenericElementReplacements);

startupPostPropertyLoadTasks.push(passBodySizeToCpp);

startupPostPropertyLoadTasks.push(retreiveFeralUICalendarBackgroundURL);

//Inform C++/loading screen that startup is truely finished
startupCompleteTasks.push(startupFuncComplete);

function initialiseBuildState()
{
	var thePromise;
	
	try
	{
		thePromise = Promise.allFinish(
			[
				hookPropertyToFunction("MainIsDebug",
													"bool",
					function(propertyName, typePattern, propValueArray)
					{
						debugMode = propValueArray[0];
					})
				,
				hookPropertyToFunction("MainIsTesterMode",
													"bool",
					function(propertyName, typePattern, propValueArray)
					{
						testerMode = propValueArray[0];
					})
			]);
		
		thePromise = thePromise.then(
			function()
			{
				logToConsole = testerMode;

				initialiseLogging();
			});

	}
	catch(e)
	{
		if(feral && feral.log)
			feral.log("We can't even tell if we are a debug/GM build, so we can't log to console!");
		else
			console.error("Failed to detect feral JS extension on startup");
		
		thePromise = Promise.reject(e);
	}
	
	return thePromise;
}

function initialiseLoadingScreen()
{
	var promise = Promise.resolve();
	
	var loadingScreentext = $("#loadingText[data-inner-string]");

	if(loadingScreentext.length > 0)
	{
		loadingScreentext = $(loadingScreentext[0]);
		
		promise = hookPropertyToElement(loadingScreentext.data("innerString"),
										"string",
										loadingScreentext[0]);
		
		promise = promise.then(
			function()
			{
				loadingScreentext.removeClass("loadingTextHidden");
			});
	}

	// Load a game specific intro video if there is one.
	var startupVideo = $("#startupVideo");
	var videoSources = startupVideo.children('source');
	$.get('../../GamePGOW/images/feral.mp4')
		.done(function()
		{
			var mp4Video = videoSources.filter('[type="video/mp4"]');
			mp4Video.attr('src', '../../GamePGOW/images/feral.mp4#t=2.6');

			startupVideo[0].load();
		});

	$.get('../../GamePGOW/images/feral.webm')
		.done(function()
		{
			var webmVideo = videoSources.filter('[type="video/webm"]');
			webmVideo.attr('src', '../../GamePGOW/images/feral.webm#t=2.6');

			startupVideo[0].load();
		});
	
	promise = promise.then(
		function()
		{
			setTimeout(
				function()
				{
					$("#startupVideo").css({opacity: 1})
				}, 200);
		});
	
	return promise;
}

function initialiseLanguageClasses()
{
	var respondToGettingLanguage =
		function(propertyName, typePattern, propValueArray)
		{
			var languageString = propValueArray[0];
			
			$("html").addClass("lang" + languageString);
		};
	
	var promise = hookPropertyToFunction(	"MainLanguageClass",
											"string",
											respondToGettingLanguage);
	
	return promise;
}

function initialiseDeliveryClasses()
{
	var respondToGettingDelivery =
		function(propertyName, typePattern, propValueArray)
		{
			var deliveryString = propValueArray[0];

			$("html").addClass("delivery" + deliveryString);
		}

	var promise = hookPropertyToFunction(	"MainDeliveryClass",
											"string",
											respondToGettingDelivery);

	return promise;
}

function initialiseUpdateHtmlImport()
{
	var respondToGettingUpdateFile =
		function(propertyName, typePattern, propValueArray)
		{
			var urlString = propValueArray[0];
			
			if(urlString !== "")
			{
				var scriptFile = document.createElement('script');
				scriptFile.setAttribute("type","text/javascript");
				scriptFile.setAttribute("src", urlString);
				
				document.body.appendChild(scriptFile);
			}
		};
	
	var promise = hookPropertyToFunction(	"MainUpdateFileURL",
											"string",
											respondToGettingUpdateFile);
	
	return promise;
}

//Replaces generic form-style elements with jqueryUI custom elements
function initialiseGenericElementReplacements()
{
	return initialiseGenericElementReplacementsWithinElement(document);
}

//Replaces generic form-style elements with jqueryUI custom elements
function initialiseGenericElementReplacementsWithinElement(element)
{
	$( ".buttonset", element ).buttonset({ items: "input[type=button]:not(.noDisplay)" });
	$( "input[type=button]", element ).button();
	
	$( "label>input[type=checkbox]", element ).parent().addClass("checkbox");
	
	//Not all selects want to be selectricated, e.g. the version string list
	$( ".selectBox", element ).selectric();
	
	return Promise.resolve();
}

//Let the c++ know how big the webpage is, so it can size the window appropriately.
function passBodySizeToCpp()
{
	var docHeight = document.body.offsetHeight;
	var docWidth  = document.body.offsetWidth;
	
	var promise = registerWriteOnlyProperty("MainBodyResolution",
											"int,int");
	
	
	promise = promise.then(
		function(response)
		{
			return setWriteOnlyPropertyValue(	"MainBodyResolution",
												"int,int",
												[docWidth, docHeight]);
		});
	
	return promise;
}

function retreiveFeralUICalendarBackgroundURL()
{
	return hookPropertyToFunction(	"regString-appRegKey-FeralUICalendarBackgroundURL",
									"string",
									forwardRequestedFeralUICalendarBackground);
}

function forwardRequestedFeralUICalendarBackground(propertyName, typePattern, propValueArray)
{
	var thePromise = Promise.resolve();
	
	if (propValueArray.length > 0 && propValueArray[0].length > 0)
	{
		var outputPropertyName = "FeralUIFullCalendarBackgroundURL-" + propValueArray[0];

		thePromise = hookPropertyToFunction(outputPropertyName,
											"string",
											applyFeralUICalendarBackground);
	}
	
	return thePromise;
}

function applyFeralUICalendarBackground(propertyName, typePattern, propValueArray)
{
	if (propValueArray.length > 0 && propValueArray[0].length > 0)
	{
		var imagePath = propValueArray[0];
		$( "#tabView" ).prepend('<img src="' + imagePath + '"/>');
	}
}

function StartupStart()
{
	var promise = registerWriteOnlyProperty("mainStartupStart", "");
	
	promise = promise.then(
		function(response)
		{
			return setWriteOnlyPropertyValue("mainStartupStart", "", []);
		});
	
	return promise;
}


function startupFuncComplete()
{
	// Give focus to window so keyboard events are recognised without needing to click the screen
	$(window).focus();

	var promise = registerWriteOnlyProperty("MainPropLoadComplete", "");
	
	promise = promise.then(
		function(response)
		{
			return setWriteOnlyPropertyValue("MainPropLoadComplete", "", []);
		}).then(
		function(response)
		{
			var startupVideo = $("#startupVideo");
			if(startupVideo.length !== 0 && startupVideo[0].play !== undefined)
			{
				startupVideo[0].play();
			}
			//We aren't done until any knock-on events are fired, so only consider us done when this event can fire
			//As a bonus, this makes the loading div fade away more smoothly
			//Now at 1 second since transitions during startup can last up to that long, 
			//and there have been a number of glitches caused by startup that might be fixed by such a delay
			//1 second was overkill. Knock it down to half a second.
			window.setTimeout(StartupDone, 500);
		});
	
	return promise;
}

function StartupDone()
{
	var promise = registerWriteOnlyProperty("mainStartupDone", "");
	
	promise = promise.then(
		function(response)
		{
			return setWriteOnlyPropertyValue("mainStartupDone", "", []);
		}).then(
		function(response)
		{
			$("#loadingOverlay").addClass("loadingFinished");
			
			var postStartEventsDone = Date.now();
			
			console.log("Time of post-startup events/timeouts:", postStartEventsDone - startupFinishedTime);

			console.log("Total time from main script load:", postStartEventsDone - mainScriptStartTime);
			
			$("html").css( "min-width", "0px" );
			$("html").css( "min-height", "0px" );
			
			startupDone = true;
		});
	return promise;
}

